#!/usr/bin/python
# -*- coding: UTF-8 -*-

from kpautos.engine.case import Case
from kptest.config.enum import DeviceType, HostType, DeviceUtility


class NET_CARD_BASIC_TOOL_API_003(Case):
    """
        Name:
            NET_CARD_BASIC_TOOL_API_003
        Label:
            网卡逻辑状态关闭测试
        PreCondition:

        TestStep:
            1) 1、关闭SUT端所有网口ifconfig ethX down
                2、开启SUT端所有网口：ifconfig ethX up
        ExpectedResult:
            A) 1、SUT端网口可以被开启
        Parameters:

        Author:
            XXXXXX
        Last Modified:
            xxxx-xx-xx
        Remark:

    """

    # 测试执行前配置等准备操作
    def pre_test_case(self):
        self.logger.info("Pre Test Case Start.... ")
        self.device_dut = self.resource.get_device(device_type=DeviceType.Server, utility=DeviceUtility.DUT)
        self.os_host = self.device_dut.get_host(host_type=HostType.HostOS)
        self.os_ip = self.os_host.local_ip

    # 测试步骤
    def procedure(self):
        self.log_step("Step1: 1、关闭SUT端所有网口ifconfig ethX down")
        res = self.os_host.network.ifconfig(all=True)
        self.logger.info(f"测试前查询到得端口信息为：{res}")
        for _ in res:
            if _.get('ip') == self.os_ip:
                continue
            else:
                self.os_host.network.ifconfig(nic_name=_.get('name'), action='down')
                down_res = self.os_host.network.ifconfig(nic_name=_.get('name'))[0]
                self.assertEqual(down_res.get('link'), 'DOWN', f"测试失败，端口关闭失败:{_.get('name')}")

        self.log_step("Step2: 2、打开SUT端所有网口ifconfig ethX up")
        res = self.os_host.network.ifconfig(all=True)
        self.logger.info(f"测试前查询到得端口信息为：{res}")
        for _ in res:
            if _.get('ip') == self.os_ip:
                continue
            else:
                self.os_host.network.ifconfig(nic_name=_.get('name'), action='up')
                self.os_host.network.ifconfig(nic_name=_.get('name'))

    # 测试结束后恢复环境
    def post_test_case(self):
        self.log_step("恢复环境: 1、打开SUT端所有网口")
        res = self.os_host.network.ifconfig(all=True)
        for _ in res:
            if _.get('ip') == self.os_ip:
                continue
            else:
                self.os_host.network.ifconfig(nic_name=_.get('name'), action='up')
                self.os_host.network.ifconfig(nic_name=_.get('name'))
